package com.ndp.fb.rdb.db.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.ndp.fb.rdb.api.VpiCountryInfoRdbService;
import com.ndp.fb.rdb.db.BatchPstAssign;
import com.ndp.fb.rdb.db.DaoTemplate;
import com.ndp.fb.rdb.db.impl.mapper.DefaultRowMapper;
import com.ndp.fb.rdb.model.VpiCountryInfo;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by Mikey.zhaopeng on 2015/3/19 13:25.
 * Email mikey.zhao@ndpmedia.com
 */
@Service
public class VpiCountryInfoRdbServiceImpl extends DaoTemplate implements VpiCountryInfoRdbService {
    @Override
    public void save(final VpiCountryInfo obj) {
        String sql = "INSERT INTO `vpi_country_info` (`vpi_info_id`, `country_code`, `country_name`) VALUES (?, ?, ?)";
        saveResultId(sql, ps -> setObject(ps, obj));
    }

    @Override
    public void save(List<VpiCountryInfo> vpiCountryInfos) {
        String sql = "INSERT INTO `vpi_country_info` (`vpi_info_id`, `country_code`, `country_name`) VALUES (?, ?, ?)";
        BatchPstAssign<VpiCountryInfo> bps = (ps, vpiCountryInfo) -> setObject(ps, vpiCountryInfo);
        this.batchSaveResultId(sql, bps, vpiCountryInfos);
    }

    private void setObject(PreparedStatement ps, VpiCountryInfo vpiCountryInfo) throws SQLException {
        ps.setObject(1, vpiCountryInfo.getVpiInfoId());
        ps.setObject(2, vpiCountryInfo.getCountryCode());
        ps.setObject(3, vpiCountryInfo.getCountryName());
    }

    @Override
    public void update(VpiCountryInfo vpiCountryInfo) {
        String sql = "UPDATE `vpi_country_info` SET `vpi_info_id`=?, `country_code`=?, `country_name`=? WHERE `id`=?";
        this.getJdbcTemplate().update(sql, vpiCountryInfo.getVpiInfoId(), vpiCountryInfo.getCountryCode(), vpiCountryInfo.getCountryName(), vpiCountryInfo.getId());
    }


    @Override
    public VpiCountryInfo findById(Long id) {
        String sql = "SELECT * from vpi_country_info where id = ?";
        return this.getJdbcTemplate().queryForObject(sql, DefaultRowMapper.autoRowMapper(VpiCountryInfo.class), id);
    }


    @Override
    public VpiCountryInfo findByVpiInfoIdAndCountryCode(Long vpiInfoId, String countryCode)
    {
        String sql = "SELECT * FROM vpi_country_info WHERE 1=1 AND vpi_info_id = ? AND country_code = ?";
        return findOne(sql, new Object[]{vpiInfoId,countryCode}, DefaultRowMapper.autoRowMapper(VpiCountryInfo.class));
    }
}
